(function () {
    $.fn.imageUpload = function (options) {
        var defaultOptions = {
            tableName: "Common",//分类
            limitCount: 1,//每次上传图片数上限
            hiddenInputId: undefined,
            defaultImg: undefined,
            uploadText: undefined,
            host: undefined,//图片服务器
            readonly: false//是否只读
        };
        var uploadOptions = $.extend(defaultOptions, options);
        var idPrefix = "";
        var uploadId = Math.floor(Math.random() * 100000000 + 1).toString();
        if ($.trim($(this).html()) == "") {
            $(this).html("");
            var uploadHtml = '<table class="uploadimage-out" cellpadding="0" cellspacing="0">' +
                                '<tr ><td>' +
                                    '<ul id="imageUploadUl' + uploadId + '" class="uploadimage-ul">' +
                                    (uploadOptions.defaultImg ? '<li id="imageUploadDefault"><img src="' + uploadOptions.defaultImg + '" height="50px" width="50px"/></li>' : "") +
                                    '</ul>' +
                                    '<div id="imageUploadBox' + uploadId + '" style="float:left;margin-top:8px;margin-left:8px;">' +
                                        '<div class="fileinput-button uploadimage-btn">' +
                                             (uploadOptions.defaultImg ? '<span style="position: absolute;top: 15px;left: 12px;">修改</span>' : '<i class="plus"></i>') +
                                             '<input id="imageUpload' + uploadId + '" alt="' + uploadId + '" type="file"  name="upload"   accept="image/jpeg,image/png,image/gif,image/bmp"  class="uploadimage-input"  multiple/>' +
                                         '</div>' +
                                         '<span class="uploadimage-remark"' + (uploadOptions.defaultImg ? 'style="display:none;"' : "") + '>' + (uploadOptions.uploadText ? uploadOptions.uploadText : "最多" + uploadOptions.limitCount + "张图片") + '</span> ' +
                                     '</div>' +
                                 '</td></tr>' +
                              '</table>';
            idPrefix = "imageUpload";
            $(this).html(uploadHtml);
        } else {
            idPrefix = $(this).find("input").eq(0).attr("id");
            if (uploadId != undefined) {
                uploadId = "";
            }
        }
        var curCount = 0;             //当前数量
        var fileUploadCount = 0;      //上传完成的数量
        var isLoad = false;           //是否加载
        //初始化上传控件
        function init() {
            if (uploadOptions.readonly) {
                $('#imageUploadBox' + uploadId).remove();
                return;
            }
            //图片上传加载
            $('#' + idPrefix + uploadId).fileupload({
                url: "/Common/Upload?tableName=" + uploadOptions.tableName,
                dataType: 'text',                            //返回值类型为text
                autoUpload: true,                            //不是自动上传
                acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, //可上传的类型：gif,jpg,jpeg,png
                maxFileSize: 5000000, // 5 MB                //最大上传：5MB
                limitMultiFileUploads: 1,                    //限制选择文件数量：1
                limitConcurrentUploads: uploadOptions.limitCount,  //限制当前文件上传数量：1
                disableImageResize: /Android(?!.*Chrome)|Opera/
                                   .test(window.navigator.userAgent), //android和opera不支持图片预览
                imageMaxHeight: 5000,
                previewMaxWidth: 50,                        //图片预览宽度
                previewMaxHeight: 50,                       //图片预览高度
                previewCrop: true
            }).on('fileuploadadd', function (e, data)     //添加文件（图片）的事件
            {
                uploadId = this.alt;
                curCount++;

                isLoad = true;
                if (curCount > uploadOptions.limitCount) {
                    layer.msg("最多只能上传" + uploadOptions.limitCount + "张图片！");
                    isLoad = false;
                    return false;
                }
                if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(data.files[0].name)) {
                    layer.msg("只能上传jpg/jpeg/gif/png类型的图片！");
                    isLoad = false;
                    curCount--;
                    return false;
                }
                if (data.files[0].size > 5000000) {
                    layer.msg("上传图片不能大于5MB！");
                    isLoad = false;
                    curCount--;
                    return false;
                }
            }).on('fileuploadsubmit', function (e, data)// 添加文件后准备上传的事件
            {
                if (!isLoad) {
                    curCount--;
                    return false;
                }
                if (uploadOptions.defaultImg) {
                    $("#imageUploadDefault").html('<img src="/Content/image/loading.gif" height="50px" width="50px"/>');
                } else {
                    $('#' + idPrefix + 'Ul' + uploadId).append('<li class="imageUpload-loading"><img src="/Content/image/loading.gif" height="50px" width="50px"/></li>');
                }
            }).on('fileuploaddone', function (e, data)//上传成功
            {
                var jsonObj = eval('(' + data.result + ')');
                switch (jsonObj.state) {
                    case "error":
                        $('#' + idPrefix + 'Ul' + uploadId).find("li:last-child").remove();
                        curCount--;
                        layer.msg(jsonObj.message);
                        break;
                    case "success":
                        addItem(jsonObj.data);
                        break;
                }
            });
        }
        function addItem(imgSrc, isInit) {
            fileUploadCount++;
            //修改加载图片为上传后台图片
            var fullSrc = imgSrc;
            if (!!uploadOptions.host) {
                fullSrc = uploadOptions.host + fullSrc;
            }
            var aId = "a" + uploadId + fileUploadCount;
            var imgHtml = '<a id="' + aId + '" data-img="' + imgSrc + '"><img style="width:52px;height:52px;" src="' + fullSrc + '!60X60" layer-src="' + fullSrc + '"/></a>';
            if (isInit) {
                var imgLi = $("<li></li>");
                imgLi.html(imgHtml);
                $('#' + idPrefix + 'Ul' + uploadId).append(imgLi);
            } else {
                var liObj = $('#' + idPrefix + 'Ul' + uploadId).find(".imageUpload-loading").eq(0);
                liObj.html(imgHtml);
                liObj.removeClass("imageUpload-loading");
                $("#" + uploadOptions.hiddenInputId).val(getImgStr());
            }

            $("#imageUploadDefault").html(imgHtml);

            //点击图片
            $("#" + aId).click(function (obj) {
                if (uploadOptions.readonly) {
                    layer.photos({
                        photos: '#imageUploadUl' + uploadId, shift: 5
                    });
                } else {
                    layer.confirm("您确定要删除该图片?", {
                        icon: "fa-exclamation-circle",
                        title: "删除图片",
                        btn: ['确认', '取消'],
                        btnclass: ['btn btn-primary', 'btn btn-danger'],
                    }, function (index) {
                        deleteItem(aId);
                        layer.close(index);
                    }, function () {
                        //callBack(false)
                    });
                }
            });
        }
        //删除图片
        function deleteItem(aId) {
            $("#" + aId).parent().remove();
            curCount--;
            fileUploadCount--;
            $("#" + uploadOptions.hiddenInputId).val(getImgStr());
        }
        //获取图片字符串函数
        function getImgStr() {
            var liArray = $('#' + idPrefix + 'Ul' + uploadId).find("li");
            var imgStr = "";
            for (var i = 0; i < liArray.length; i++) {
                imgStr = imgStr + "," + liArray.eq(i).find("a").attr("data-img");
            }
            return imgStr.substr(1);
        };

        //初始化图片
        function initItems() {
            var imgSrc = $("#" + uploadOptions.hiddenInputId).val();
            if (imgSrc == undefined || imgSrc.length == 0) return;
            var imgs = imgSrc.split(",");
            for (var i = 0; i < imgs.length; i++) {
                var img = imgs[i];
                curCount++;
                addItem(img, true);
            }
        };
        //获取图片字符串函数赋予
        uploadOptions.getImgStr = function () {
            return getImgStr();
        };
        //获取图片字符串函数赋予
        uploadOptions.clearImg = function () {
            $('#' + idPrefix + 'Ul' + uploadId).html("");
            curCount = 0;
            fileUploadCount = 0;
        };
        //运行初始化
        init();
        //初始化图片
        initItems();
    };
})(jQuery);
